package com.cuiweiyou.adbctoller;

import com.cuiweiyou.adbctoller.bean.DeviceModel;
import com.cuiweiyou.adbctoller.bean.WechatNumberModel;
import com.cuiweiyou.adbctoller.shell.AdbExec;
import com.cuiweiyou.adbctoller.shell.AdbExec.OnGetDeviceSNListListener;
import com.cuiweiyou.adbctoller.ui.ChatLoopUI;
import com.cuiweiyou.adbctoller.ui.CtrollerUI;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnAcceptingClickListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnChatGroupClickListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnChatingClickListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnChooseWXListFileListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnChooseWorkSpaceListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnFlushDevicesListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnInstallTestClickListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnInstallWxAppClickListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnPullActionClickListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnPullDbClickListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnSearchClickListener;
import com.cuiweiyou.adbctoller.ui.CtrollerUI.OnSelectAllDeviceClickListener;
import com.cuiweiyou.adbctoller.ui.LoadingUI;
import com.cuiweiyou.adbctoller.ui.SearchingUI;
import com.cuiweiyou.adbctoller.util.DateUtil;
import com.cuiweiyou.adbctoller.util.FileUtil;
import com.cuiweiyou.adbctoller.util.LineSeparatorUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * www.gaohaiyan.com
 */
public class TestMain {
    static CtrollerUI ctroller;
    private static SearchingUI searchingUI;
    private static ChatLoopUI chatLoopUI;
    private static LoadingUI loadingUI;

    public static void main(String[] args) {

        ctroller = new CtrollerUI();
        ctroller.setUiEnable(false);
        ctroller.setOnSearchClickListener(onSearchClickListener);
        ctroller.setOnPullDbClickListener(onPullDbClickListener);
        ctroller.setOnChatingClickListener(onChatingClickListener);
        ctroller.setOnAcceptingClickListener(onAcceptingClickListener);
        ctroller.setOnChatGroupClickListener(onChatGroupClickListener);
        ctroller.setOnChooseWorkSpaceListener(onChooseWorkSpaceListener);
        ctroller.setOnPullActionClickListener(onPullActionClickListener);
        ctroller.setOnChooseWXListFileListener(onChooseWXListFileListener);
        ctroller.setOnInstallTestClickListener(onInstallTestClickListener);
        ctroller.setOnInstallWxAppClickListener(onInstallWxAppClickListener);
        ctroller.setOnSelectAllDeviceClickListener(onSelectAllDeviceClickListener);
        ctroller.setOnFlushDevicesListener(onFlushDevicesListener);

        new AdbExec().getDeviceSNList(new OnGetDeviceSNListListener() {
            @Override
            public void onGetDeviceSNList(boolean success, List<DeviceModel> list, List<String> log) {
                FileUtil.saveLog("初始化手机列表");
                ctroller.saveLogs(log);

                // if (success) {
                ctroller.setData(list);

                if (FileUtil.isExistsFileOrFloder(Constant.sourceWorkSpace)) {
                    FileUtil.createDiffDeviceFile(list); // 初始化应用
                    FileUtil.createDiffFriendFile(list); // 初始化应用
                    FileUtil.createDiffGimmickFile(list); // 初始化应用
                }
                // }
                ctroller.setUiEnable(true);
            }
        });

    }

    static OnFlushDevicesListener onFlushDevicesListener = new OnFlushDevicesListener() {
        @Override
        public void onFlushDevices() {
            FileUtil.saveLog("刷新手机列表");
            ctroller.setUiEnable(false);

            new AdbExec().getDeviceSNList(new OnGetDeviceSNListListener() {
                @Override
                public void onGetDeviceSNList(boolean success, List<DeviceModel> list, List<String> log) {

                    ctroller.setData(list);

                    if (FileUtil.isExistsFileOrFloder(Constant.sourceWorkSpace)) {
                        FileUtil.createDiffDeviceFile(list); // 刷新设备
                        FileUtil.createDiffFriendFile(list); // 刷新设备
                        FileUtil.createDiffGimmickFile(list); // 刷新设备
                    }

                    ctroller.setUiEnable(true);

                    if (FileUtil.isExistsFileOrFloder(Constant.sourceWorkSpace)) {
                        ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("刷新设备列表，是否有设备：", (success ? (list.size() > 0) : 0) + ""));
                        if (success) {
                            ctroller.saveLogs(LineSeparatorUtil.transformDeviceToListLog("刷新设备", list));
                        }
                    }
                }
            });
        }
    };

    static OnChooseWXListFileListener onChooseWXListFileListener = new OnChooseWXListFileListener() {

        @Override
        public void onChoosedWXListFile(String filePath) {
            FileUtil.saveLog("选择微信名单：" + filePath);
            List<WechatNumberModel> friendList = new AdbExec().getWechatNumberList(filePath);

            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("名单文件：", "微信数量：" + friendList.size()));
            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("文件目录：", filePath));

            ctroller.setAllWxFriendList(friendList);
            List<String> log = new ArrayList<>();
            for (int i = 0; i < friendList.size(); i++) {
                log.add(DateUtil.getNowYYMMDDHHmmss() + "_加载微信号：" + friendList.get(i).toString());
            }
            ctroller.saveLogs(log);
        }
    };

    static OnInstallWxAppClickListener onInstallWxAppClickListener = new OnInstallWxAppClickListener() {

        @Override
        public void onInstallWxAppClick(List<DeviceModel> deviceList, String wxFilePath) {
            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("安装 wechat app", "" + deviceList.size()));

            loadingUI = new LoadingUI("正在安装微信app，请等待...", ctroller);

            if (deviceList.size() > 0) {
                new AdbExec().installWXApp(deviceList, wxFilePath, new AdbExec.OnProcessFinishListener() {
                    @Override
                    public void finish(String note, List<String> log) {
                        loadingUI.dispose();
                        ctroller.setUiEnable(true);
                        ctroller.showToast("安装 wechat app完成");
                        ctroller.saveLogs(log);
                    }

                    @Override
                    public void error(List<String> log) {
                        loadingUI.dispose();
                        ctroller.setUiEnable(true);
                        ctroller.showToast("安装 wechat app失败了");
                        ctroller.saveLogs(log);
                    }
                });
            }
        }
    };

    static OnInstallTestClickListener onInstallTestClickListener = new OnInstallTestClickListener() {

        @Override
        public void onInstallTestClick(List<DeviceModel> deviceList, String app_debug_androidTest_Path, String app_debug_Path) {
            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("安装 test app", "" + deviceList.size()));

            loadingUI = new LoadingUI("正在安装测试client端apk，请等待...", ctroller);

            new AdbExec().installTestApp(deviceList, app_debug_androidTest_Path, app_debug_Path, new AdbExec.OnProcessFinishListener() {
                @Override
                public void finish(String note, List<String> log) {
                    loadingUI.dispose();
                    ctroller.setUiEnable(true);
                    ctroller.showToast("安装 test app完成");
                    ctroller.saveLogs(log);
                }

                @Override
                public void error(List<String> log) {
                    loadingUI.dispose();
                    ctroller.setUiEnable(true);
                    ctroller.showToast("安装 test app失败了");
                    ctroller.saveLogs(log);
                }
            });
        }
    };

    static OnSearchClickListener onSearchClickListener = new OnSearchClickListener() {

        @Override
        public void onSearchClick(List<DeviceModel> deviceList, List<WechatNumberModel> friendList, int diffMinTime, int diffMaxTime, String hello, String deviceFilePath) {
            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("添加新好友", "" + deviceList.size()));

            searchingUI = new SearchingUI(//
                                          "正在查找添加朋友，请等待...", //
                                          ctroller, //
                                          new SearchingUI.OnStopSearchingListener() {
                                              @Override
                                              public void onStopSearching() {
                                                  ctroller.saveLogs(new ArrayList<String>() {
                                                      {
                                                          add(DateUtil.getNowYYMMDDHHmmss() + "_强制停止查找添加朋友");
                                                      }
                                                  });
                                                  System.exit(0);
                                              }
                                          });


            new AdbExec().testSearching(//
                                        deviceList, //
                                        friendList, //
                                        diffMinTime, //
                                        diffMaxTime,//
                                        hello,//
                                        deviceFilePath,//
                                        ctroller.isSameFriends(), new AdbExec.OnProcessFinishListener() {
                        @Override
                        public void finish(String note, List<String> log) {
                            searchingUI.dispose();
                            ctroller.setUiEnable(true);
                            ctroller.showToast("添加新好友完成");
                            ctroller.saveLogs(log);
                        }

                        @Override
                        public void error(List<String> log) {
                            searchingUI.dispose();
                            ctroller.setUiEnable(true);
                            ctroller.showToast("添加新好友失败了");
                            ctroller.saveLogs(log);
                        }
                    });

        }
    };

    static OnAcceptingClickListener onAcceptingClickListener = new OnAcceptingClickListener() {
        @Override
        public void onAcceptingClick(List<DeviceModel> deviceList) {
            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("陌生好友主动请求通过", "点击了" + deviceList.size()));

            loadingUI = new LoadingUI("正在通过陌生人的请求，请等待...", ctroller);

            new AdbExec().testAccepting(deviceList, new AdbExec.OnProcessFinishListener() {
                @Override
                public void finish(String note, List<String> log) {
                    loadingUI.dispose();
                    ctroller.setUiEnable(true);
                    ctroller.showToast("陌生好友主动请求处理完成");
                    ctroller.saveLogs(log);
                }

                @Override
                public void error(List<String> log) {
                    loadingUI.dispose();
                    ctroller.setUiEnable(true);
                    ctroller.showToast("陌生好友主动请求处理失败了");
                    ctroller.saveLogs(log);
                }
            });
        }
    };

    static OnChatingClickListener onChatingClickListener = new OnChatingClickListener() {
        @Override
        public void onChattingClick(List<DeviceModel> deviceList, String gimmickCommFilePath, String gimmickHelloFilePath, String wordFilePath, String deviceFilePath, int diffMinTime, int diffMaxTime) {
            boolean keep = ctroller.isKeep();
            boolean sameGimmicks = ctroller.isSameGimmicks();
            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("遍历新聊天", "使用统一话术：" + sameGimmicks + "，点击了" + deviceList.size() + "，是否常驻：" + keep + "，comm话术文件：" + gimmickCommFilePath));
            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("遍历新聊天", "使用统一话术：" + sameGimmicks + "，点击了" + deviceList.size() + "，是否常驻：" + keep + "，hello话术文件：" + gimmickHelloFilePath));

            chatLoopUI = new ChatLoopUI( //
                                         ctroller, //
                                         new ChatLoopUI.OnStopChatLoopListener() {
                                             @Override
                                             public void onStopChatLoop() {
                                                 boolean b = ctroller.stopKeep();
                                                 System.out.println("是否停止了：" + b);
                                             }
                                         });

            loopChatting(deviceList, gimmickCommFilePath, gimmickHelloFilePath, wordFilePath, deviceFilePath, sameGimmicks, diffMinTime, diffMaxTime);
        }
    };

    private static void loopChatting(List<DeviceModel> deviceList, String gimmickCommFilePath, String gimmickHelloFilePath, String wordFilePath, String deviceFilePath, boolean isSameGimmicks, int diffMinTime, int diffMaxTime) {
        FileUtil.saveLog("聊天process");

        new AdbExec()//
                .testChatting(//
                              deviceList, //
                              gimmickCommFilePath, //
                              gimmickHelloFilePath, //
                              wordFilePath, //
                              deviceFilePath,//
                              isSameGimmicks, //
                              new AdbExec.OnProcessFinishListener() {
                                  @Override
                                  public void finish(String note, List<String> log) {
                                      if (ctroller.isKeep()) {

                                          long start = System.currentTimeMillis();
                                          System.out.println(start);
                                          int diff = new Random().nextInt(diffMaxTime - diffMinTime) + diffMinTime;
                                          Observable//
                                                  .timer(diff, TimeUnit.SECONDS)//
                                                  .subscribe(new Consumer<Long>() {
                                                      @Override
                                                      public void accept(Long aLong) throws Exception {
                                                          long stop = System.currentTimeMillis();
                                                          System.out.println("延迟聊天：" + (stop - start));

                                                          loopChatting(deviceList, gimmickCommFilePath, gimmickHelloFilePath, wordFilePath, deviceFilePath, isSameGimmicks, diffMinTime, diffMaxTime);
                                                      }
                                                  });
                                      } else {
                                          chatLoopUI.closeWindow();
                                          ctroller.setUiEnable(true);
                                          ctroller.showToast("监听消息完成");
                                          ctroller.saveLogs(log);
                                      }
                                  }

                                  @Override
                                  public void error(List<String> log) {
                                      ctroller.setUiEnable(true);
                                      ctroller.showToast("监听消息失败了");
                                      ctroller.saveLogs(log);
                                  }
                              });
    }

    static OnPullDbClickListener onPullDbClickListener = new OnPullDbClickListener() {
        @Override
        public void onPullDbClick(List<DeviceModel> deviceList, int flag) {
            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("提取设备的操作日志db-点击了", "" + deviceList.size()));
            loadingUI = new LoadingUI("正在提取日志，请等待...", ctroller);

            String outPath = Constant.sourceWorkSpace + "log/";
            if (null == outPath || "".equals(outPath)) {
                outPath = "~/Desktop/";
            }
            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("提取设备的操作日志，保存路径：", outPath));

            new AdbExec().testPullSqlites(outPath, deviceList, flag, new AdbExec.OnProcessFinishListener() {
                @Override
                public void finish(String note, List<String> log) {
                    loadingUI.dispose();
                    ctroller.setUiEnable(true);
                    ctroller.showToast("提取设备的操作日志完成\n" + note);
                    ctroller.saveLogs(log);
                }

                @Override
                public void error(List<String> log) {
                    loadingUI.dispose();
                    ctroller.setUiEnable(true);
                    ctroller.showToast("提取设备的操作日志失败了");
                    ctroller.saveLogs(log);
                }
            });
        }
    };

    static OnChatGroupClickListener onChatGroupClickListener = new OnChatGroupClickListener() {

        @Override
        public void onChatGroupClick(List<DeviceModel> deviceList) {
            System.out.println("群聊天点击了" + deviceList.size());
        }
    };

    static OnSelectAllDeviceClickListener onSelectAllDeviceClickListener = new OnSelectAllDeviceClickListener() {

        @Override
        public void onSelectAllDeviceClick(List<DeviceModel> deviceList) {
            FileUtil.saveLog("选择了设备，数量：" + deviceList.size());

            if (0 == deviceList.size()) {
                ctroller.showToast("没有设备哦");
            }
        }
    };

    static OnPullActionClickListener onPullActionClickListener = new OnPullActionClickListener() {
        @Override
        public void onPullActionClick(List<DeviceModel> deviceList) {
            FileUtil.saveLog("拉取Client端动作日志");

            loadingUI = new LoadingUI("正在提取动作日志，请等待...", ctroller);

            String outPath = Constant.sourceWorkSpace;
            if (null == outPath || "".equals(outPath)) {
                outPath = "~/Desktop/";
            }

            ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("action日志保存路径：", outPath));

            new AdbExec().testPullActions(//
                                          outPath, //
                                          deviceList, //
                                          new AdbExec.OnProcessFinishListener() {
                                              @Override
                                              public void finish(String note, List<String> log) {
                                                  loadingUI.dispose();
                                                  ctroller.setUiEnable(true);
                                                  ctroller.showToast("提取设备的action logs完成" + note);
                                                  ctroller.saveLogs(log);
                                              }

                                              @Override
                                              public void error(List<String> log) {
                                                  loadingUI.dispose();
                                                  ctroller.setUiEnable(true);
                                                  ctroller.showToast("提取设备的action logs失败了");
                                                  ctroller.saveLogs(log);
                                              }
                                          });
        }
    };

    static OnChooseWorkSpaceListener onChooseWorkSpaceListener = new OnChooseWorkSpaceListener() {
        @Override
        public void onChoosedWorkSpace(String path, List<DeviceModel> allDevices) {
            if (null != path && !"".equals(path)) {
                Constant.sourceWorkSpace = path;
                Constant.lastLogFilePath = FileUtil.createLogFile(); // 初始化日志文件

                FileUtil.createDiffDeviceFile(allDevices); // 选择了工资资源目录
                FileUtil.createDiffFriendFile(allDevices); // 选择了工资资源目录
                FileUtil.createDiffGimmickFile(allDevices); // 选择了工资资源目录
                FileUtil.createLogFolder(); // 选择了工资资源目录

                ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("资源目录设置了：", Constant.sourceWorkSpace));
                ctroller.saveLogs(LineSeparatorUtil.transformStrigToListLog("选择了目录", path));
                ctroller.saveLogs(LineSeparatorUtil.transformDeviceToListLog("为每个手机创建配置文件", allDevices));

                ctroller.loadFriendList();
            }
        }
    };
}
